package com.wangbo.basic;

import lombok.experimental.UtilityClass;

/**
 * 稀疏数组工具类
 */
@UtilityClass
public class SparseArrayUtil {

    /**
     * 矩阵 -> 稀疏数组
     */
    public int[][] toSparseArray(int[][] matrix) {
        if (isEmpty(matrix))
            throw new CustomException(400, "矩阵不能为空");

        int rowNum = matrix.length;
        int colNum = matrix[0].length;

        int notDefaultNum = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] != 0)
                    notDefaultNum++;
            }
        }

        int[][] sparseArray = new int[notDefaultNum + 1][3];
        sparseArray[0][0] = rowNum;
        sparseArray[0][1] = colNum;
        sparseArray[0][2] = notDefaultNum;

        int count = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] != 0) {
                    count++;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = matrix[i][j];
                }
            }
        }

        return sparseArray;
    }

    /**
     * 稀疏数组 -> 矩阵
     */
    public int[][] toMatrix(int[][] sparseArray) {
        int[][] matrix = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i < sparseArray.length; i++) {
            matrix[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        return matrix;
    }

    /**
     * 矩阵是否为空
     */
    public boolean isEmpty(int[][] matrix) {
        if ((matrix == null || matrix.length == 0) || (matrix.length == 1 && matrix[0].length == 0)) {
            return true;
        }
        return false;
    }
}
